﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Diagnostics;

namespace Zero.UControl.Demo.Views.UAdorner.Component
{
    public class ScaleAdorner : ElementDecoratorBase
    {
        private Thumb _thumb;
        private VisualCollection _visuals;

        public ScaleAdorner(UIElement adornedElement) : base(adornedElement)
        {
            _visuals = new VisualCollection(this);
            _thumb = new Thumb
            {
                Width = 10,
                Height = 10,
                Background = Brushes.Blue,
                Cursor = Cursors.SizeNWSE
            };

            _thumb.DragDelta += Thumb_DragDelta;
            _visuals.Add(_thumb);
        }

        public override void Attach(UIElement element, Canvas canvas)
        {
            base.Attach(element, canvas);

            var adornerLayer = AdornerLayer.GetAdornerLayer(element);
            if (adornerLayer != null)
            {
                adornerLayer.Add(new ScaleAdorner(element));
            }
        }

        private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            if (AdornedElement is FrameworkElement fe)
            {
                TransformUtil.EnsureTransformGroup(fe);
                var scale = TransformUtil.GetScale(fe);

                double scaleDelta = 0.01 * Math.Max(e.HorizontalChange, e.VerticalChange);

                scale.ScaleX = Math.Max(0.1, scale.ScaleX + scaleDelta);
                scale.ScaleY = Math.Max(0.1, scale.ScaleY + scaleDelta);

                // 手动触发布局更新,通知其他的装饰器进行变化
                AdornerLayer.GetAdornerLayer(fe)?.Update(fe);
            }
        }


        protected override Size ArrangeOverride(Size finalSize)
        {
            if (AdornedElement is FrameworkElement fe)
            {
                double scaledWidth = fe.ActualWidth;
                double scaledHeight = fe.ActualHeight;

                // 让 Thumb 按照缩放后的尺寸摆放在右下角
                _thumb.Arrange(new Rect(scaledWidth - 5, scaledHeight - 5, 10, 10));
            }

            return finalSize;
        }

        protected override int VisualChildrenCount => _visuals.Count;
        protected override Visual GetVisualChild(int index) => _visuals[index];
    }

}
